package ordersubmit

import (
	// "fmt"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/types"
	"mall/service/user/rpc/userclient"
	// "github.com/sirupsen/logrus"
	// "github.com/zeromicro/go-zero/core/logx"
)

// AddressInfoHandler 地址信息handler
type AddressInfoHandler struct {
	// 合成复用Next
	Next
}

// Do 地址信息逻辑
func (h *AddressInfoHandler) Do(c *Context) (err error) {
	if c.OrderType == globalkey.OrderTypeVirtual {
		c.Resp.AddressValid = true
		return
	}

	// logx.Infow("获取地址信息...")

	preload := "userAddress:Id,UserId,Label,Consignee,Mobile,Province,City,District,Street,DetailedAddress,PostalCode,RegionCode,IsDefault"
	var filters []string
	filters = append(filters, "UserId,equalTo:"+strconv.FormatUint(c.UserId, 10))
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	if c.Req.AddressId != nil && *c.Req.AddressId > 0 {
		filters = append(filters, "Id,equalTo:"+strconv.FormatUint(*c.Req.AddressId, 10))
	}

	res, err := c.SvcCtx.UserRpc.GetUserAddressList(c.Ctx, &userclient.BaseListReq{
		Limit:      uint32(1),
		Preload:    pointy.GetPointer(preload),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(c.UserId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return err
	}

	// logx.Infow("地址信息校验...")

	var isValid bool
	if len(res.List) > 0 {
		for _, v := range res.List {
			if v.RegionCode == nil || len(*v.RegionCode) == 0 {
				continue
			}

			c.Resp.Address = &types.UserAddressInfo{
				Id:              v.Id,
				UserId:          v.UserId,
				Label:           v.Label,
				Consignee:       v.Consignee,
				Mobile:          v.Mobile,
				Province:        v.Province,
				City:            v.City,
				District:        v.District,
				Street:          v.Street,
				DetailedAddress: v.DetailedAddress,
				PostalCode:      v.PostalCode,
				RegionCode:      v.RegionCode,
				IsDefault:       v.IsDefault,
			}
			isValid = true
			break
		}
	}

	c.Resp.AddressValid = isValid

	return
}
